package com.cool.modules.finance.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.cool.core.annotation.CoolRestController;
import com.cool.core.base.BaseController;
import com.cool.core.exception.CoolException;
import com.cool.core.util.CoolSecurityUtil;
import com.cool.modules.base.entity.sys.table.BaseSysUserEntityTableDef;
import com.cool.modules.finance.entity.account.FinanceAccountEntity;
import com.cool.modules.finance.entity.account.FinanceTrialBalanceEntity;
import com.cool.modules.finance.entity.account.table.FinanceAccountEntityTableDef;
import com.cool.modules.finance.entity.account.table.FinanceTrialBalanceEntityTableDef;
import com.cool.modules.finance.service.account.FinanceTrialBalanceService;
import com.cool.modules.finance.service.family.FinanceUserFamilyService;
import com.mybatisflex.core.query.QueryWrapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Tag(name = "账户管理", description = "账户管理")
@CoolRestController(api = { "add", "delete","page" })
@RequiredArgsConstructor
public class AdminFinanceTrialBalanceController extends BaseController<FinanceTrialBalanceService, FinanceTrialBalanceEntity> {

    final FinanceUserFamilyService userFamilyService;

    @Override
    protected void init(HttpServletRequest request, JSONObject requestParams) {
        FinanceTrialBalanceEntity trialBalanceEntity = requestParams.toBean(FinanceTrialBalanceEntity.class);
        Date[] dateRange = CollectionUtil.isNotEmpty(trialBalanceEntity.getDateRange())?trialBalanceEntity.getDateRange().toArray(Date[]::new):new Date[0];
        Date[] trialRange = CollectionUtil.isNotEmpty(trialBalanceEntity.getTrialRange())?trialBalanceEntity.getTrialRange().toArray(Date[]::new) : new Date[0];

        FinanceTrialBalanceEntityTableDef trialBalance = FinanceTrialBalanceEntityTableDef.FINANCE_TRIAL_BALANCE_ENTITY;
        FinanceAccountEntityTableDef account = FinanceAccountEntityTableDef.FINANCE_ACCOUNT_ENTITY.as("account");
        BaseSysUserEntityTableDef sysUser = BaseSysUserEntityTableDef.BASE_SYS_USER_ENTITY;

        List<Long> userIds = userFamilyService.getFamilyUserIdsByUserId(CoolSecurityUtil.getCurrentUserId());
        if (null == userIds) {
            throw new CoolException("当前用户没有绑定家庭，请先绑定家庭再试");
        }
        QueryWrapper queryWrapper = new QueryWrapper().select(trialBalance.ALL_COLUMNS,
                        account.ACCOUNT_NAME.as(FinanceTrialBalanceEntity::getAccountName),
                        sysUser.NAME.as(FinanceTrialBalanceEntity::getAccountUserName)
                ).
                from(trialBalance).leftJoin(account).on(trialBalance.ACCOUNT_ID.eq(account.ID)).
                leftJoin(sysUser).on(account.OWNED_ACCOUNT.eq(sysUser.ID)).
                where(trialBalance.ACCOUNT_ID.eq(trialBalanceEntity.getAccountId()).when(trialBalanceEntity.getAccountId() != null)).
                and(account.OWNED_ACCOUNT.in(userIds)).
                and(trialBalance.REDEEM_DATE.between(dateRange).when(CollectionUtil.isNotEmpty(trialBalanceEntity.getDateRange()))).
                and(trialBalance.TRIAL_DATE.between(trialRange).when(CollectionUtil.isNotEmpty(trialBalanceEntity.getTrialRange()))).
                and(trialBalance.COIN_ID.eq(trialBalanceEntity.getCoinId()).when(trialBalanceEntity.getCoinId() != null)).
                and(trialBalance.IS_FINAL.eq(trialBalanceEntity.getIsFinal()).when(trialBalanceEntity.getIsFinal() != null));
        if (trialBalanceEntity.getAccountId()!=null){
            queryWrapper.
                    orderBy(FinanceTrialBalanceEntity::getIsFinal,false).
                    orderBy(FinanceTrialBalanceEntity::getTrialDate,false);
        }
        setPageOption(createOp().keyWordLikeFields(account.ACCOUNT_NAME, sysUser.NAME).queryWrapper(queryWrapper));
    }

    @Override
    protected FinanceTrialBalanceEntity buildSubData(QueryWrapper queryWrapper) {
        FinanceTrialBalanceEntity entity = new FinanceTrialBalanceEntity();
        List<FinanceTrialBalanceEntity> list = service.list(queryWrapper);
        entity.setDays(list.stream().map(FinanceTrialBalanceEntity::getDays).reduce(0L,Long::sum));
        entity.setCapital(list.stream().map(FinanceTrialBalanceEntity::getCapital).reduce(BigDecimal.ZERO, BigDecimal::add));
        entity.setInterest(list.stream().map(FinanceTrialBalanceEntity::getInterest).reduce(BigDecimal.ZERO, BigDecimal::add));
        return entity;
    }
}
